# -*- coding: utf-8 -*-
"""
demo.py
"""
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import os
import json

from tornado.options import define, options
define("port", default=8002, help="run on the given port", type=int)


def check_file(path):
	"""检查文件是否存在"""
	if not os.path.exists(path):
		with open(path, 'w') as f:
			f.write('')

class MainHandler(tornado.web.RequestHandler):

	def set_default_headers(self):
		self.set_header('Access-Control-Allow-Origin', '*')
		self.set_header("Access-Control-Allow-Headers", "x-requested-with")
		self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')

	def get(self):
		uuid = self.get_argument('uuid', '')
		login_status = self.get_argument('status', '')
		data = {}
		if uuid:
			path = os.path.join(os.path.dirname(__file__), 'static\img\uuid.txt')
			check_file(path)
			with open(path) as f:
				uuid = f.read()
			data['uuid'] = 'https://login.weixin.qq.com/qrcode/%s'%uuid if uuid else ''

		if login_status:
			path = os.path.join(os.path.dirname(__file__), 'static\img\login_status.txt')
			check_file(path)
			with open(path) as f:
				login_status = f.read() or ''
			data['status'] = login_status

		self.write(json.dumps(data))


if __name__ == "__main__":
	handlers_list = [
		(r"/", MainHandler), 
		]
	tornado.options.parse_command_line()
	settings = dict(
	    template_path=os.path.join(os.path.dirname(__file__), "templates"),
	    static_path=os.path.join(os.path.dirname(__file__), "static"),
	    debug=True,
	)
	app = tornado.web.Application(handlers=handlers_list, **settings)
	http_server = tornado.httpserver.HTTPServer(app)
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()

"""
python demo.py --port=8881
end demo.py
"""